package com.ophiux.wechat.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ophiux.wechat.mapper.OphiuxOrderRegisterMapper;
import com.ophiux.wechat.model.OphiuxOrderRegisterDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desc:
 * @author: hhl
 * @date：2023/5/4 17:11
 */
@RestController
@RequestMapping("/notify")
@Api(tags = "发送模板通知")
@Slf4j
public class NotifyController {
    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;

    @Value("${wechat.templateId}")
    private String templateId;


    @Autowired
    OphiuxOrderRegisterMapper ophiuxOrderRegisterMapper;

    /**
     * {{first.DATA}}
     * 就诊时间：{{keyword1.DATA}}
     * 就诊项目：{{keyword2.DATA}}
     * 回访内容：{{keyword3.DATA}}
     * {{remark.DATA}}
     *
     * @return
     */
    @GetMapping
    @ApiOperation("发送服务满意度调查通知  -  测试")
    public String test() {
        long startTime = System.currentTimeMillis();
        String openid = "ouMU4wEF6j-KjNwFtxxmM0G6uRSo";
//        String openid = "oFLQ21pNCnFft2RqksAbl4V0FWfo";
        List<OphiuxOrderRegisterDto> list = ophiuxOrderRegisterMapper.getOrderRegisterList();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
        String tokenStr = HttpUtil.post(url, "");
        JSONObject object = JSON.parseObject(tokenStr);
        if (!ObjectUtils.isEmpty(object.getString("errcode"))) {
            log.info("获取accessToken失败，{}", tokenStr);
            return tokenStr;
        }
        String accessToken = object.getString("access_token");
        System.out.println(accessToken);

//        accessToken = "68_nXh_CQwtOtDexrBUq-XemwccKzV8cODEfIvnyEhS0nBxadfQdiNtY9w7lrPxW_Ld9sRDcIyuZCF-rt_9L_g6uwIBkTRfpIC-azMraGF5fsQVPJwVSEiiEgYa-_UEHYaAJAJMD";
        String pushUrl = String.format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s", accessToken);

        OphiuxOrderRegisterDto dto = new OphiuxOrderRegisterDto();
        dto.setOtherId(openid);
        dto.setDeptName("骨科");
        dto.setId("122116");
        dto.setVisitDate("2023-05-04");
        try {
            Map dataMap = new HashMap();
            dataMap.put("touser", openid);
            dataMap.put("template_id", templateId);
            dataMap.put("url", "http://wx.hongrenyiyuan.com:8916/HospWechatMVC/oauthNew/wechat?moduleURL=/oauthNew/oauth-login?logSucUrl=/appointrecord/message-evaluate?id=" + dto.getId());
            Map dynamicDataMap = new HashMap();
            dataMap.put("data", dynamicDataMap);

            Map keyword1Map = new HashMap();
            keyword1Map.put("value", dto.getVisitDate());
            dynamicDataMap.put("keyword1", keyword1Map);

            Map keyword2Map = new HashMap();
            keyword2Map.put("value", dto.getDeptName());
            dynamicDataMap.put("keyword2", keyword2Map);

            Map keyword3Map = new HashMap();
            keyword3Map.put("value", "为了更好的提供服务，就诊结束后，请您评价下医生的就诊服务。");
            dynamicDataMap.put("keyword3", keyword3Map);

            log.info("发送模板消息 {} {} {}", pushUrl, System.lineSeparator(), JSONUtil.toJsonStr(dataMap));
            String result = HttpUtil.post(pushUrl, JSON.toJSONString(dataMap));
            log.info("发送模板消息 结果 {}", result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            long endTime = System.currentTimeMillis();
            log.info("发送模板消息 用时{}毫秒", endTime - startTime);
        }
        return "通知成功";
    }

    @GetMapping("/sendNotify")
    @ApiOperation("发送服务满意度调查通知  -  正式")
    public String sendNotify() {
        long startTime = System.currentTimeMillis();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
        String tokenStr = HttpUtil.post(url, "");
        JSONObject object = JSON.parseObject(tokenStr);
        if (!ObjectUtils.isEmpty(object.getString("errcode"))) {
            log.info("获取accessToken失败，{}", tokenStr);
            return tokenStr;
        }
        String accessToken = object.getString("access_token");
        System.out.println(accessToken);

        String pushUrl = String.format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s", accessToken);

        List<OphiuxOrderRegisterDto> list = ophiuxOrderRegisterMapper.getOrderRegisterList();
        for (OphiuxOrderRegisterDto dto : list) {
            try {

                Map dataMap = new HashMap();
                dataMap.put("touser", dto.getOtherId());
                dataMap.put("template_id", templateId);
                dataMap.put("url", "http://wx.hongrenyiyuan.com:8916/HospWechatMVC/oauthNew/wechat?moduleURL=/oauthNew/oauth-login?logSucUrl=/appointrecord/message-evaluate?id=" + dto.getId());
                Map dynamicDataMap = new HashMap();
                dataMap.put("data", dynamicDataMap);

                Map keyword1Map = new HashMap();
                keyword1Map.put("value", dto.getVisitDate());
                dynamicDataMap.put("keyword1", keyword1Map);

                Map keyword2Map = new HashMap();
                keyword2Map.put("value", dto.getDeptName());
                dynamicDataMap.put("keyword2", keyword2Map);

                Map keyword3Map = new HashMap();
                keyword3Map.put("value", "为了更好的提供服务，就诊结束后，请您评价下医生的就诊服务。");
                dynamicDataMap.put("keyword3", keyword3Map);

                log.info("发送模板消息 {} {} {}", pushUrl, System.lineSeparator(), JSONUtil.toJsonStr(dataMap));
                String result = HttpUtil.post(pushUrl, JSON.toJSONString(dataMap));
                log.info("发送模板消息 结果 {}", result);

            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
        long endTime = System.currentTimeMillis();
        log.info("发送模板消息 用时{}毫秒", endTime - startTime);
        return "通知成功";
    }
}
